<template>
  <div class="AAG_module">
    <module-header
      :title="title"
      :meter="meter"
      :params="{
        module: 'AAG',
        status: selectRecordStatus,
        Id: selectRecordId,
        Bore: init_params.AAG701,
        Cutting: init_params.AAG601
      }"
    />
    <section class="settings">
      <div class="item">
        <span>出厂编号</span>
        <el-input v-model="init_main_params.AAF001" disabled size="mini" />
        <span class="unit"></span>
      </div>
      <div class="item">
        <span>口径</span>
        <el-input v-model="init_params.AAG701" size="mini" />
        <span class="unit">mm</span>
      </div>
      <div class="item">
        <span>转换器型号</span>
        <el-input v-model="init_main_params.AAF1301" disabled size="mini" />
        <span class="unit"></span>
      </div>
      <div class="item">
        <span>表体图号</span>
        <el-input v-model="init_params.AAG801" size="mini" />
        <span class="unit"></span>
      </div>
      <div class="item">
        <span>接管内径</span>
        <el-input v-model="init_params.AAG101" size="mini" />
        <span class="unit">mm</span>
      </div>
      <div class="item">
        <span>转换器编号</span>
        <el-input v-model="init_params.AAG501" size="mini" />
        <span class="unit"></span>
      </div>
      <div class="item">
        <span>下位机版本</span>
        <el-input v-model="init_main_params.AAF4901" disabled size="mini" />
        <span class="unit"></span>
      </div>
      <div class="item">
        <span>表体编号</span>
        <el-input v-model="init_params.AAG601" size="mini" />
        <el-upload
          class="upload-demo"
          action=""
          :disabled="selectRecordId === '' || !init_button_limit.AAG_4"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="readLocaleExcel"
        >
          <el-button
            slot="trigger"
            :disabled="selectRecordId === '' || !init_button_limit.AAG_4"
            size="mini"
            type="primary"
          >
            手动选择三坐标
          </el-button>
        </el-upload>
      </div>
    </section>
    <section class="table">
      <record-table
        title="装配记录表"
        procedure="AAG"
        :meter="meter"
        :limits="RecordTableLimit"
        :params="{
          title,
          Cutting: init_params.AAG601
        }"
        :tableColumnDict="tableColumnDict"
        @onRecordSelect="onRecordSelect"
        @onRecordStore="onRecordStore"
        @onRecordDelete="onRecordDelete"
      />
    </section>
    <section :class="`tabs ${currentSeries}`">
      <template v-if="currentSeries === 'S'">
        <div class="row">
          <div class="time-item">
            <span>测量声程时间</span>
            <el-select
              v-model="comboxValue.AAG1901"
              size="mini"
              :disabled="selectRecordId === ''"
              @change="onComboxChange($event, 'AAG1901')"
            >
              <el-option
                v-for="option in comboxOptions.AAG1901"
                :key="option.Savetime"
                :label="option.Savetime"
                :value="option.Savetime"
              />
            </el-select>
          </div>
          <div class="time-item">
            <span>反推声程时间</span>
            <el-select
              v-model="comboxValue.AAG2001"
              size="mini"
              :disabled="selectRecordId === ''"
              @change="onComboxChange($event, 'AAG2001')"
            >
              <el-option
                v-for="option in comboxOptions.AAG2001"
                :key="option.Savetime"
                :label="option.Savetime"
                :value="option.Savetime"
              />
            </el-select>
          </div>
          <div class="time-item">
            <span>备注</span>
            <el-input
              type="text"
              size="mini"
              :disabled="selectRecordId === ''"
              placeholder="请填写备注信息"
            />
          </div>
        </div>
        <div class="row">
          <div class="time-item">
            <span>测量声程时间【后四声道】</span>
            <el-select
              v-model="comboxValue.AAG1902"
              size="mini"
              :disabled="
                selectRecordId === '' || generateChannelNum(init_main_params.AAF1301) !== 8
              "
              @change="onComboxChange($event, 'AAG1902')"
            >
              <el-option
                v-for="option in comboxOptions.AAG1902"
                :key="option.Savetime"
                :label="option.Savetime"
                :value="option.Savetime"
              />
            </el-select>
          </div>
          <div class="time-item">
            <span>反推声程时间【后四声道】</span>
            <el-select
              v-model="comboxValue.AAG2002"
              size="mini"
              :disabled="
                selectRecordId === '' || generateChannelNum(init_main_params.AAF1301) !== 8
              "
              @change="onComboxChange($event, 'AAG2002')"
            >
              <el-option
                v-for="option in comboxOptions.AAG2002"
                :key="option.Savetime"
                :label="option.Savetime"
                :value="option.Savetime"
              />
            </el-select>
          </div>
        </div>
        <div class="channel-table">
          <el-table
            :data="formatedChannelData"
            size="mini"
            border
            :span-method="computedSpanMethod"
            style="width: 100%"
          >
            <el-table-column
              v-for="(column, key) in channelColumnDict"
              :key="key"
              :prop="key"
              :label="column"
              :min-width="key === 'channel' ? 80 : 150"
            >
              <template v-if="key === 'model'" slot="header">
                <div class="model-header">
                  <span>型号</span>
                  <!-- <el-button type="primary" size="mini" @click="logoutData">读取型号</el-button> -->
                </div>
              </template>
              <template v-if="key !== 'channel'" v-slot="scope">
                <el-input
                  size="mini"
                  v-model="formatedChannelData[scope.$index][key]"
                  placeholder="请输入"
                  :disabled="isEditDisabled"
                  @blur="onInputChange(key, scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template v-else>
        <div class="row">
          <div class="sub_row">
            <div class="item">
              <span>测量声程时间【前四声道】</span>
              <el-select
                v-model="comboxValue.AAG1901"
                size="mini"
                :disabled="selectRecordId === ''"
                @change="onComboxChange($event, 'AAG1901')"
              >
                <el-option
                  v-for="option in comboxOptions.AAG1901"
                  :key="option.Savetime"
                  :label="option.Savetime"
                  :value="option.Value"
                />
              </el-select>
            </div>
            <div class="item">
              <span>反推声程时间【前四声道】</span>
              <el-select
                v-model="comboxValue.AAG2001"
                size="mini"
                :disabled="selectRecordId === ''"
                @change="onComboxChange($event, 'AAG2001')"
              >
                <el-option
                  v-for="option in comboxOptions.AAG2001"
                  :key="option.Savetime"
                  :label="option.Savetime"
                  :value="option.Value"
                />
              </el-select>
            </div>
            <div class="item">
              <span>处理板编号</span>
              <el-input
                v-model="init_params.AAG2901"
                :disabled="selectRecordId === ''"
                size="mini"
                placeholder="请输入"
              />
            </div>
          </div>
          <div class="sub_row">
            <div class="item">
              <span>测量声程时间【后四声道】</span>
              <el-select
                v-model="comboxValue.AAG1902"
                size="mini"
                :disabled="
                  selectRecordId === '' || generateChannelNum(init_main_params.AAF1301) !== 8
                "
                @change="onComboxChange($event, 'AAG1902')"
              >
                <el-option
                  v-for="option in comboxOptions.AAG1902"
                  :key="option.Savetime"
                  :label="option.Savetime"
                  :value="option.Value"
                />
              </el-select>
            </div>
            <div class="item">
              <span>反推声程时间【后四声道】</span>
              <el-select
                v-model="comboxValue.AAG2002"
                size="mini"
                :disabled="
                  selectRecordId === '' || generateChannelNum(init_main_params.AAF1301) !== 8
                "
                @change="onComboxChange($event, 'AAG2002')"
              >
                <el-option
                  v-for="option in comboxOptions.AAG2002"
                  :key="option.Savetime"
                  :label="option.Savetime"
                  :value="option.Value"
                />
              </el-select>
            </div>
            <div class="item">
              <span>备注</span>
              <el-input
                v-model="init_params.AAG401"
                type="textarea"
                size="mini"
                placeholder="请填写备注信息"
                resize="none"
                :rows="1"
                :disabled="selectRecordId === ''"
              />
            </div>
          </div>
          <div class="sub_row">
            <span>表格导出</span>
            <div class="item range">
              <el-input v-model="OEM.lower" size="mini" placeholder="请输入起始表号" />
              <span>-</span>
              <el-input v-model="OEM.upper" size="mini" placeholder="请输入结束表号" />
            </div>
            <el-upload
              class="upload-demo"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleOEM"
            >
              <el-button type="primary" size="mini">OEM</el-button>
            </el-upload>
          </div>
          <div class="sub_row">
            <span>温度传感器</span>
            <el-input
              v-model="init_params.AAG3001"
              :disabled="selectRecordId === ''"
              size="mini"
              placeholder="请输入"
            />
            <div class="item range">
              <el-input v-model="init_main_params.AAF5101" size="mini" disabled />
              <span>-</span>
              <el-input v-model="init_main_params.AAF5001" size="mini" disabled />
              <span>℃</span>
            </div>
          </div>
          <div class="sub_row">
            <span>压力传感器</span>
            <el-input
              v-model="init_params.AAG3101"
              :disabled="selectRecordId === ''"
              size="mini"
              placeholder="请输入"
            />
            <div class="item range">
              <el-input v-model="init_main_params.AAF5301" size="mini" disabled />
              <span>-</span>
              <el-input v-model="init_main_params.AAF5201" size="mini" disabled />
              <span>MPa</span>
            </div>
          </div>
        </div>
        <!-- 声道表格 -->
        <div class="channel-table">
          <el-table
            :data="formatedChannelData"
            size="mini"
            border
            :span-method="computedSpanMethod"
            style="width: 100%"
          >
            <el-table-column
              v-for="(column, key) in channelColumnDict"
              :key="key"
              :prop="key"
              :label="column"
              :min-width="key === 'channel' ? 80 : 150"
            >
              <template v-if="key === 'model'" slot="header">
                <div class="model-header">
                  <span>型号</span>
                  <!-- <el-button type="primary" size="mini" @click="logoutData">读取型号</el-button> -->
                </div>
              </template>
              <template v-if="key !== 'channel'" v-slot="scope">
                <el-input
                  size="mini"
                  v-model="formatedChannelData[scope.$index][key]"
                  placeholder="请输入"
                  :disabled="selectRecordId === ''"
                  @blur="onInputChange(key, scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </section>
    <section v-if="isSelectCardShow" class="popover">
      <div class="popover-content">
        <div class="title">
          <h4>请选择表类型</h4>
          <h6>根据表号的不同，用户可操作的数据项会存在一定差别，请谨慎选择</h6>
        </div>
        <div class="row">
          <div
            :class="{
              card: true,
              isSelect: preSeries === '2M'
            }"
            @click="preSeries = '2M'"
          >
            <div class="card-content">
              <i class="iconfont icon-form"></i>
              <h4>2M 类型</h4>
              <span>包括前缀为 WA4 | WA6 | WA9 | WAB 的表号</span>
            </div>
          </div>
          <div
            :class="{
              card: true,
              isSelect: preSeries === 'S'
            }"
            @click="preSeries = 'S'"
          >
            <div class="card-content">
              <i class="iconfont icon-form" />
              <h4>S 类型</h4>
              <span>包括前缀为 WA1 | WA8 的表号</span>
            </div>
          </div>
        </div>
        <div class="footer" @click="confirmSelectMeter">确认选择该表号？</div>
      </div>
    </section>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import XLSX from 'xlsx'
import { Component, Prop, Watch } from 'vue-property-decorator'
import { Getter } from 'vuex-class'
import { tableColumnDict, ChannelColumnType, channelColumnDict, channelTableData } from './params'
import ModuleHeader from '@/components/basic/ModuleHeader.vue'
import RecordTable from '@/components/basic/RecordTable.vue'
import { GetDataByMeter } from '@/api/dashboard'
import {
  GetProcedureRecordData,
  GetComboxList,
  GetProcedureButtonLimit,
  UpdateProcedureRecord
} from '@/api/procedure'
import { OEM } from '@/api/OEM'
import { AxiosResponse } from 'axios'
import { deepClone, formatTime } from '@/utils/specificFunc'
import { Message } from 'element-ui'
import { Dictionary } from '@/interface/Basic'
import { json2xlsx } from '@/utils/file'
interface ComboxOptionType {
  Savetime: string
  Value: Dictionary<string>
}
interface ComboxListType {
  Label: string
  options: ComboxOptionType[]
}
@Component({
  components: {
    ModuleHeader,
    RecordTable
  }
})
class AAG extends Vue {
  @Getter('name') username!: string
  @Getter('sidebar') sidebar!: { opened: boolean }
  @Prop() status!: string
  @Prop({ default: '' }) meter!: string
  @Prop({ required: true }) title!: string
  preSeries: '2M' | 'S' | '' = ''
  currentSeries: '2M' | 'S' = '2M'
  isSelectCardShow: boolean = false
  init_main_params: Dictionary<string> = {
    AAF001: '',
    AAF1301: '',
    AAF4901: '',
    AAF5101: '',
    AAF5001: '',
    AAF5301: '',
    AAF5201: ''
  }
  init_params: Dictionary<string> = {
    // header
    AAG601: '',
    AAG701: '',
    AAG801: '',
    AAG101: '',
    AAG501: '',
    // tab
    AAG401: '',
    AAG2901: '',
    AAG3001: '',
    AAG3101: ''
  }
  init_button_limit: Dictionary<boolean> = {
    // 保存
    AAG_0: false,
    // 删除
    AAG_1: false,
    // 新建
    AAG_2: true,
    // 读取三坐标
    AAG_3: true,
    // 手动选择三坐标
    AAG_4: true
  }
  meter_params: {
    '2M': Dictionary<string>
    S: Dictionary<string>
  } = {
    '2M': {},
    S: {
      AAG401: ''
    }
  }
  isEditDisabled: boolean = true
  channelColumnDict = channelColumnDict
  channelTableData = channelTableData
  formatedChannelData: ChannelColumnType[] = []
  tableColumnDict = tableColumnDict
  comboxOptions: Dictionary<ComboxOptionType[]> = {}
  comboxValue: Dictionary<string> = {
    AAG1901: '',
    AAG1902: '',
    AAG2001: '',
    AAG2002: ''
  }
  selectRecordId: string = ''
  selectRecordStatus: string = ''
  OEM = {
    upper: '',
    lower: ''
  }
  scannerBlocks: Dictionary<string> = {}
  get RecordTableLimit(): Dictionary<boolean> {
    const { AAG_0, AAG_1, AAG_2 } = this.init_button_limit
    return {
      Store: AAG_0,
      Create: AAG_2,
      Delete: AAG_1
    }
  }
  @Watch('meter')
  meter_handler(newVal: string) {
    const prefix = newVal.slice(0, 3)
    if (['WA1', 'WA8'].includes(prefix)) this.currentSeries = 'S'
    else if (['WA4', 'WA6', 'WA9', 'WAB'].includes(prefix)) this.currentSeries = '2M'
    else return 'S'
  }
  @Watch('init_main_params.AAF1301', { deep: true })
  cs_handler(newVal: string) {
    this.channelTableData = this.channelTableData.slice(0, this.generateChannelNum(newVal) * 2)
    this.initChannelTableData()
    this.initScannerValues()
  }
  mounted() {
    if (!this.meter) {
      this.isSelectCardShow = true
    }
    this.selectRecordStatus = this.status
    this.initComboxOptions()
    this.initDashboardParams()
    this.$broadOn('onEnterProcedure', (e: Dictionary<string>) => {
      this.updateParams(e)
    })
    this.$broadOn('onDirectiveCollected', (e: { fullPath: string; value: string }) => {
      const { fullPath, value } = e
      if (fullPath === this.$route.fullPath) {
        console.log(fullPath, value)
        this.fillDataByScanner(value)
      }
    })
  }
  initScannerValues() {
    const defaultKeys = ['AAG2901', 'AAG3001', 'AAG3101']
    const v_list = defaultKeys.reduce((obj, key) => {
      const newObj: Dictionary<string> = {}
      newObj[key] = ''
      return { ...obj, ...newObj }
    }, {} as Dictionary<string>)
    const { AAF1301 } = this.init_main_params
    const channel_num = this.generateChannelNum(AAF1301)
    this.channelTableData.slice(0, channel_num * 2).map(item => {
      v_list[item[1].key] = ''
    })
    this.scannerBlocks = v_list
  }
  fillDataByScanner(v: string) {
    console.log(v)
    const defaultKeys = ['AAG2901', 'AAG3001', 'AAG3101']
    defaultKeys.forEach(key => {
      this.scannerBlocks[key] = this.init_params[key] || ''
    })
    this.channelTableData.forEach((channel, index) => {
      channel.forEach(item => {
        if (item.prop === 'number') {
          this.scannerBlocks[item.key] = this.formatedChannelData[index].number
        }
      })
    })
    const empty_key = Object.keys(this.scannerBlocks).find(k => this.scannerBlocks[k] === '')
    if (!empty_key) return
    if (defaultKeys.includes(empty_key)) {
      this.init_params[empty_key] = v
      console.log(this.init_params)
    } else {
      this.channelTableData.forEach((channel, index) => {
        channel.forEach(item => {
          if (item.prop === 'number' && item.key === empty_key) {
            this.formatedChannelData[index].number = v
            console.log(this.formatedChannelData)
          }
        })
      })
    }
  }
  confirmSelectMeter() {
    if (!this.preSeries) return
    this.isSelectCardShow = false
    this.currentSeries = this.preSeries
  }
  // 将原始 channelData 对象数组转换为 el-table 需要的格式
  initChannelTableData() {
    this.formatedChannelData = this.channelTableData.map(row => {
      const obj: ChannelColumnType = {
        channel: '',
        number: '',
        model: '',
        standard: '',
        angle: '',
        axial: '',
        measure: '',
        actual: ''
      }
      row.forEach(item => {
        // key 不为 static 时，数据应该为动态数据，可以从后台获取
        if (item.key === 'static') obj[item.prop as keyof ChannelColumnType] = item.value
        else obj[item.prop as keyof ChannelColumnType] = item.value
      })
      return obj
    })
  }
  initComboxOptions() {
    GetComboxList({ Number: this.meter }).then(
      (res: AxiosResponse<{ ReturnData: ComboxListType[] }>) => {
        const { ReturnData } = res.data
        this.comboxOptions = ReturnData.reduce((accu, next) => {
          const obj: Dictionary<ComboxOptionType[]> = {}
          obj[next.Label] = next.options
          return { ...accu, ...obj }
        }, {})
      }
    )
  }
  initDashboardParams() {
    GetDataByMeter(this.meter).then((res: AxiosResponse<{ ReturnData: Dictionary<string> }>) => {
      const { ReturnData } = res.data
      Object.keys(this.init_main_params).forEach(key => {
        if (ReturnData[key]) {
          this.init_main_params[key] = ReturnData[key]
        }
      })
    })
  }
  initButtonsLimit(limitCode: string) {
    GetProcedureButtonLimit({ SeNumber: limitCode, DatabaseLabel: 'AAG' }).then(
      (res: AxiosResponse<{ ReturnData: Dictionary<boolean> }>) => {
        const { ReturnData } = res.data
        Object.keys(ReturnData).forEach(key => {
          if (Object.hasOwnProperty.call(this.init_button_limit, key)) {
            this.init_button_limit[key] = ReturnData[key]
          }
        })
      }
    )
  }
  // 手动选择三坐标
  readLocaleExcel(file: { name: string; raw: File }) {
    if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
      this.$message({
        message: '上传格式不正确，请上传xls或者xlsx格式',
        type: 'warning'
      })
      return
    }
    const { AAF1301 } = this.init_main_params
    const channel_num = this.generateChannelNum(AAF1301)
    const fileReader = new FileReader()
    fileReader.onload = ev => {
      try {
        const data = ev.target!.result
        const workbook = XLSX.read(data, {
          type: 'binary',
          cellDates: true
        })
        const wsname = workbook.SheetNames
        const isIncludeAveSheet = wsname.includes('平均值')
        // 比较文件与表声道数是否匹配
        if (!isIncludeAveSheet && channel_num !== wsname.length * 2) {
          this.$message({
            type: 'warning',
            message: `${wsname.length * 2}声道的文件不能导入到${channel_num}声道的表中`
          })
          return
        } else if (isIncludeAveSheet && channel_num !== (wsname.length - 1) * 2) {
          this.$message({
            type: 'warning',
            message: `${(wsname.length - 1) * 2}声道的文件不能导入到${channel_num}声道的表中`
          })
          return
        }
        const angle_list: string[] = new Array(channel_num)
        const standard_list: string[] = new Array(channel_num)
        for (let i = 0; i < wsname.length; i++) {
          if (wsname[i] === '平均值') break
          const ws: any[] = XLSX.utils
            .sheet_to_json(workbook.Sheets[wsname[i]], { defval: null })
            .map((item: any) => {
              return Object.values(item)
            })
          // 更新 settings row 的数据
          const params: Dictionary<string> = {
            AAG101: ws[5][2].toFixed(4),
            // 表体编号 | 短截编号
            AAG601: String(ws[2][8]),
            // 口径
            AAG701: String(ws[0][12]),
            // 图号
            AAG801: ws[0][0].slice(3)
          }
          this.updateParams(params)
          // 更新【标准声程】和【角度】数据
          if (AAF1301.indexOf('4ZD') !== -1 || AAF1301.indexOf('8Z') !== -1) {
            // 4声道特殊处理 && 8声道特殊处理
            if (i === 0 || i === 2) {
              angle_list[i * 2 + 1] = ((ws[12][2] + ws[13][2]) / 2).toFixed(4)
              angle_list[i * 2 + 2] = ((ws[14][2] + ws[15][2]) / 2).toFixed(4)
              standard_list[i * 2 + 1] = ws[23][8].toFixed(4)
              standard_list[i * 2 + 2] = ws[23][12].toFixed(4)
            } else if (i === 1 || i === 3) {
              angle_list[i * 2 - 2] = ((ws[12][2] + ws[13][2]) / 2).toFixed(4)
              angle_list[i * 2 + 1] = ((ws[14][2] + ws[15][2]) / 2).toFixed(4)
              standard_list[i * 2 - 2] = ws[23][8].toFixed(4)
              standard_list[i * 2 + 1] = ws[23][12].toFixed(4)
            }
          } else {
            angle_list[i * 2] = ((ws[12][2] + ws[13][2]) / 2).toFixed(4)
            angle_list[i * 2 + 1] = ((ws[14][2] + ws[15][2]) / 2).toFixed(4)
            standard_list[i * 2] = ws[23][8].toFixed(4)
            standard_list[i * 2 + 1] = ws[23][12].toFixed(4)
          }
        }
        this.updateChannelData(angle_list, 'angle')
        this.updateChannelData(standard_list, 'standard')
        this.initChannelTableData()
      } catch (e) {
        return false
      }
    }
    fileReader.readAsBinaryString(file.raw)
  }
  // validateRange(key: string) {
  //   function toNum(str: string, range: 'min' | 'max') {
  //     if (range === 'min') {
  //       return isNaN(Number(str)) || str === '' ? -Infinity : Number(str)
  //     } else {
  //       return isNaN(Number(str)) || str === '' ? Infinity : Number(str)
  //     }
  //   }
  //   function toVal(val: number, min: number, max: number) {
  //     return isNaN(val)
  //       ? ''
  //       : val < min
  //       ? min.toString()
  //       : val > max
  //       ? max.toString()
  //       : val.toString()
  //   }
  //   if (key === 'AAG3001') {
  //     const { AAF5101, AAF5001 } = this.init_main_params
  //     const { AAG3001 } = this.init_params
  //     const min = toNum(AAF5101, 'min')
  //     const max = toNum(AAF5001, 'max')
  //     const val = Number(AAG3001)
  //     this.init_params.AAG3001 = toVal(val, min, max)
  //   } else if (key === 'AAG3101') {
  //     const { AAF5101, AAF5001 } = this.init_main_params
  //     const { AAG3001 } = this.init_params
  //     const min = toNum(AAF5101, 'min')
  //     const max = toNum(AAF5001, 'max')
  //     const val = Number(AAG3001)
  //     this.init_params.AAG3001 = toVal(val, min, max)
  //   }
  // }
  computedSpanMethod({ column, rowIndex }: any) {
    if (!['channel', 'number', 'model'].includes(column.property)) {
      if (rowIndex % 2 === 0) {
        return {
          rowspan: 2,
          colspan: 1
        }
      } else {
        return {
          rowspan: 0,
          colspan: 0
        }
      }
    }
  }
  onComboxChange(e: Dictionary<string>, key: string) {
    let res: {
      prop: string
      key: string
      value: string
    }[][] = []
    const copiedTableData = deepClone(this.channelTableData)
    Object.values(e).forEach((val, index) => {
      let start_idx = 0
      let end_idx = 0
      if (['AAG1901', 'AAG2001'].includes(key)) {
        start_idx = index * 2
        end_idx = index * 2 + 2
      } else {
        start_idx = (index + 4) * 2
        end_idx = (index + 5) * 2
      }
      const frame = copiedTableData.slice(start_idx, end_idx).map(sub_arr => {
        return sub_arr.map(set => {
          if (
            (['AAG1901', 'AAG1902'].includes(key) && set.prop === 'measure') ||
            (['AAG2001', 'AAG2002'].includes(key) && set.prop === 'actual')
          ) {
            set.value = val
          }
          return set
        })
      })
      res = res.concat(frame)
    })
    if (['AAG1901', 'AAG2001'].includes(key)) {
      // 前四声道
      this.channelTableData.splice(0, 4, ...res)
    } else {
      // 后四声道
      this.channelTableData.splice(4, 4, ...res)
    }
    this.initChannelTableData()
  }
  onInputChange(key: string | number, index: number) {
    const _key = key as keyof ChannelColumnType
    if (!['channel', 'number', 'model'].includes(_key)) {
      this.formatedChannelData[index % 2 === 0 ? index + 1 : index - 1][_key] =
        this.formatedChannelData[index][_key]
    }
  }
  onRecordSelect(data: Dictionary<string>) {
    const { id, status, DatabaseLabel } = data
    this.selectRecordId = id
    this.selectRecordStatus = status
    GetProcedureRecordData({ id, DatabaseLabel }).then(
      (res: AxiosResponse<{ ReturnData: Dictionary<string> }>) => {
        const { ReturnData } = res.data
        this.init_params = ReturnData
        this.channelTableData = this.channelTableData.map(arr => {
          return arr.map(row => {
            if (row.key === 'static') return row
            row.value = ReturnData[row.key] ? ReturnData[row.key] : ''
            return row
          })
        })
        this.comboxValue = {
          AAG1901: '',
          AAG2001: ''
        }
        this.initChannelTableData()
        this.initButtonsLimit(ReturnData.AAG002)
      }
    )
  }
  onRecordDelete() {
    this.selectRecordId = ''
    this.selectRecordStatus = ''
  }
  onRecordStore(params: Dictionary<string>) {
    if (params.DatabaseLabel !== 'AAG') return
    if (!params.id) {
      Message({
        type: 'warning',
        message: '未选中id，无法保存'
      })
      return
    }
    const params_AAG: Dictionary<string> = {
      Process: this.title
    }
    const Details: Dictionary<string> = this.generateTotalParams()
    Details.AAG1801 = params.Status
    Details.AAG3201 = params_AAG.Process
    Details.AAG2601 = this.username
    Details.AAG2701 = formatTime(new Date().getTime(), 'YYYY-MM-DD-hh-mm-ss')
    const total_params = { ...params, ...params_AAG, ...{ Details } }
    UpdateProcedureRecord(total_params).then((res: AxiosResponse<{ Message: string }>) => {
      this.$message({
        type: 'success',
        message: res.data.Message
      })
      // this.selectRecordId = ''
      // this.selectRecordStatus = ''
      this.$broadEmit('onRecordStoreSucceed', { procedure: this.title })
    })
  }
  updateParams(options: Dictionary<string>) {
    // 更新铭牌信息
    Object.keys(this.init_params).forEach(key => {
      this.init_params[key] = options[key] ? options[key] : this.init_params[key]
    })
  }
  updateChannelData<T>(value: Array<T>, key: string) {
    let res: {
      prop: string
      key: string
      value: string
    }[][] = []
    value.forEach((val, index) => {
      const frame = this.channelTableData.slice(index * 2, index * 2 + 2).map(sub_arr => {
        return sub_arr.map(set => {
          if (set.prop === key) {
            set.value = String(val)
          }
          return set
        })
      })
      res = res.concat(frame)
    })
    this.channelTableData = deepClone(res)
  }
  generateTotalParams() {
    const res = deepClone(this.init_params)
    for (let i = 0; i < this.channelTableData.length; i++) {
      this.channelTableData[i].forEach(channel_item => {
        const { key, prop } = channel_item
        if (key !== 'static') {
          res[key] = this.formatedChannelData[i][prop as keyof ChannelColumnType]
        }
      })
    }
    return res
  }
  generateChannelNum(AAG1301: string): number {
    if (!AAG1301) return 0
    else if (/^(2|4|8)[A-z1-9]{1,}/.test(AAG1301.split('-')[1])) {
      return Number(AAG1301.split('-')[1][0])
    } else return 2
  }
  logoutData() {
    const result: Dictionary<string> = {}
    this.formatedChannelData.forEach((item, index) => {
      const obj: Dictionary<string> = {}
      this.channelTableData[index].forEach(column => {
        if (column.prop !== 'channel') {
          obj[column.prop] = column.key
        }
      })
      Object.keys(obj).forEach(key => {
        result[obj[key]] = item[key as keyof ChannelColumnType]
      })
    })
  }
  handleOEM(file: { name: string; raw: File }) {
    if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
      this.$message({
        message: '上传格式不正确，请上传xls或者xlsx格式',
        type: 'warning'
      })
      return
    }
    const fileReader = new FileReader()
    fileReader.onload = ev => {
      try {
        const data = ev.target!.result
        const workbook = XLSX.read(data, {
          type: 'binary',
          cellDates: true
        })
        const wsname = workbook.SheetNames
        const ws: any[] = XLSX.utils.sheet_to_json(workbook.Sheets[wsname[0]], { defval: '' })
        const fianl_res: any[] = []
        const key = ws.length !== 0 ? Object.keys(ws[0])[0] : ''
        OEM(this.OEM).then((res: AxiosResponse<{ ReturnData: Dictionary<string>[] }>) => {
          const { ReturnData } = res.data
          const result = ReturnData.map(data => {
            return Object.values(data).map(li => {
              const obj: Dictionary<string> = {}
              obj[key] = li
              return obj
            })
          }).flat()
          const final_ws = [...ws, ...result]
          for (let i = 0; i < final_ws.length; i++) {
            if (/WA[1-9]/.test(final_ws[i][key])) {
              fianl_res.push(...['', final_ws[i]])
            } else {
              fianl_res.push(final_ws[i])
            }
          }
          json2xlsx(fianl_res, file.name, wsname[0])
        })
        // const a = [
        //   { WA623010110: 'DN150' },
        //   { WA623010110: 'Y1952208040548F' },
        //   { WA623010110: '22X576' },
        //   { WA623010110: '22X566' },
        //   { WA623010110: '22X579' },
        //   { WA623010110: '22X553' }
        // ]
        // XLSX.utils.sheet_add_json(workbook.Sheets[wsname[0]], a, { origin: -1 })
        // const later_ws = ws.concat(...a)
      } catch (e) {
        return false
      }
    }
    fileReader.readAsBinaryString(file.raw)
  }
}
export default AAG
</script>

<style lang="less" scoped>
@import '~@/styles/theme.less';
@import '~@/styles/layout.less';
.AAG_module {
  box-sizing: border-box;
  position: relative;
  padding: 20px;
  width: 100%;
  height: 100%;
  #flex(column, flex-start, flex-start);
  section {
    box-sizing: border-box;
    padding: 10px;
    width: 100%;
    margin-bottom: 20px;
    border-radius: 5px;
    #color(background-color, --module-bg-color);
    #shadow-color(0, 2px, 12px, 0, --primary-shadow-color);
  }
  .settings {
    flex-wrap: wrap;
    #flex(row, flex-start, flex-start);
    #color(color, --primary-text-color);
    .item {
      #flex(row, center, space-between);
      margin: 10px;
      margin-left: 0;
      span {
        white-space: nowrap;
        width: 80px;
        font-size: 14px;
        text-align: left;
        margin-right: 10px;
      }
      .el-input {
        flex: 1;
        margin-right: 10px;
      }
      .unit {
        margin: 0;
        width: 30px;
      }
    }
  }
  .table {
    flex: 1;
    max-height: 300px;
  }
  .tabs {
    flex: 1;
    width: 100%;
    margin-bottom: 0;
    transition: all 0.5s ease;
    overflow: auto;
    #flex(column, flex-start, flex-start);
    .row {
      width: 100%;
      position: relative;
      margin-bottom: 10px;
      flex-wrap: wrap;
      #flex(column, center, flex-start);
      span {
        font-size: 14px;
        min-width: 80px;
        text-align: left;
        white-space: nowrap;
        margin-right: 10px;
        #color(color, --primary-text-color);
      }
      /deep/.el-input,
      .el-textarea {
        width: 200px;
        margin-right: 20px;
      }
      .sub_row {
        width: 100%;
        #flex(row, center, flex-start);
        .item {
          margin: 5px 10px 5px 0;
          #flex(row, center, flex-start);
        }
        .range {
          span {
            min-width: auto;
            margin-right: 20px;
          }
        }
      }
    }
    .channel-table {
      width: 100%;
      .model-header {
        #flex(row, center, space-between);
      }
    }
  }
  .S {
    .row {
      #flex(row, center, flex-start);
    }
  }
  .popover {
    position: absolute;
    top: 0;
    bottom: 0;
    z-index: 5;
    left: 0;
    margin-bottom: 0;
    background-color: unset;
    backdrop-filter: blur(40px);
    transition: all 0.5s ease;
    #flex(row, center, center);
    .popover-content {
      box-sizing: border-box;
      padding: 20px;
      width: 50%;
      height: 55%;
      border: solid 1px;
      border-radius: 5px;
      #flex(column, center, space-between);
      #color(border-color, --primary-border-color);
      #color(background-color, --module-bg-color);
      #shadow-color(0, 8px, 24px, 1px, --lighter-shadow-color);
      h4,
      h6 {
        margin-block: 0;
        #color(color, --primary-text-color);
      }
      h4 {
        font-size: 24px;
        margin-bottom: 5px;
      }
      .row {
        height: 70%;
        width: 90%;
        #flex(row, center, space-between);
        .card {
          box-sizing: border-box;
          flex: 1;
          height: 100%;
          margin: 0 20px;
          padding: 20px;
          border: solid 2px;
          border-radius: 10px;
          transition: all 0.4s ease;
          cursor: pointer;
          #flex(column, center, center);
          #color(border-color, --heavier-bg-color);
          #shadow-color(0, 0, 2px, 0, --primary-shadow-color);
          .card-content {
            #flex(column, center, space-between);
            i,
            span {
              #color(color, --primary-text-color);
            }
            i {
              font-size: 148px;
            }
            span {
              font-size: 14px;
            }
          }
        }
        .isSelect {
          #color(background-color, --primary-blue-color);
          i,
          h4,
          span {
            color: #ffffff !important;
          }
        }
        .card:hover {
          transform: translateY(-10px);
          #color(border-color, --primary-blue-color);
          #shadow-color(0, 0, 12px, 2px, --primary-blue-color);
        }
      }
      .footer {
        cursor: pointer;
        text-decoration: underline;
        #color(color, --primary-text-color);
      }
      .footer:hover {
        #color(color, --primary-blue-color);
      }
    }
  }
}
</style>
